import { computed, defineComponent, ref } from "vue";
import styles from "./Toolbar.module.less";
import { analysisRolesAndOr, analysisPermissionsAndOr } from "@/common/auth/auth";
import { SyncOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons-vue";
import Filter from "./Filter/Filter";
import _ from "lodash";
export default defineComponent({
  props: {
    config: {
      type: Object,
    },
    columns: {
      type: Array,
    },
  },
  emits: ["refreshHandler", "update:columns", "search"],
  setup(props, { emit }) {
    const ori_columns = [...props.columns || []];
    // 是否有工具栏
    const hasToolbar = computed(() => {
      return props.config?.left.length > 0 || props.config?.right.length > 0;
    })
    // 刷新
    const refreshHandler = () => {
      emit("refreshHandler");
    }

    const filterVisible = ref(false);
    if (props?.config?.left?.some((x: any) => x === 'filter') || props?.config?.right?.some((x: any) => x === 'filter')) {
      document.getElementsByTagName('body')[0].addEventListener('click', (e) => {
        filterVisible.value = false;
      })
    }
    // 筛选列
    const filterColumns = (e: any) => {
      const updateTree = (arr: any[]) => {
        arr = arr.filter((x: any) => {
          let itm = x.dataIndex instanceof Array ? x.dataIndex.join('.') : x.dataIndex;
          return e.includes(itm);
        });
        arr.forEach(x => x.children && x.children.length > 0 && (x.children = updateTree(x.children)))
        return arr;
      }
      emit("update:columns", updateTree(ori_columns || []));
      props.config?.filter?.handler?.();
    }

    // 执行搜索
    const doSearch = () => {
      emit("search");
    }

    // 工具栏-按钮
    const ToolbarBtn = (item) => {
      if (typeof item === "string") {
        switch (item) {
          case "refresh":
            return (
              <a-button
                title="刷新"
                v-slots={{
                  icon: () => <SyncOutlined />,
                }}
                onClick={() => {
                  refreshHandler();
                }}
              ></a-button>
            )
          case "add":
            return (
              <a-button
                type="primary"
                v-slots={{
                  icon: () => <PlusOutlined />,
                }}
                onClick={() => {
                  props.config?.add?.handler?.();
                }}
              >
                添加
              </a-button>
            )
          case 'filter':
            return (
              <div class={styles['filter-btn']}>
                <a-button title="列设置" onClick={(e: any) => { e.stopPropagation(); filterVisible.value = !filterVisible.value }} v-slots={{
                  icon: () => <svg-icon name="filter" />
                }}>
                </a-button>
                <Filter
                  style={{ display: filterVisible.value ? 'flex' : 'none' }}
                  columns={_.cloneDeep(props?.columns).map((x: any) => {
                    x.dataIndex instanceof Array && (x.dataIndex = x.dataIndex.join('.'));
                    return x;
                  })}
                  onChange={(e: any) => { filterColumns(e) }}
                />
              </div>
            )
          case 'search':
            return (
              <a-button
                title="搜索"
                v-slots={{
                  icon: () => <SearchOutlined />,
                }}
                onClick={() => {
                  doSearch();
                }}
              ></a-button>
            )
        }
      } else {
        return item.el(this);
      }
    }
    // 工具栏-左侧
    const ToolbarLeft = () => (
      <div class={styles['toolbar-left']}>
        {
          props.config?.left
            .filter(x => (!props.config?.[x]?.permissions || analysisPermissionsAndOr(props.config?.[x].permissions)) && (!props.config?.[x]?.roles || analysisRolesAndOr(props.config?.[x].roles)))
            .map((item: any, index: number) => {
              if (item) {
                return ToolbarBtn(item);
              }
            })
        }
      </div>
    )
    // 工具栏-右侧
    const ToolbarRight = () => (
      <div class={styles['toolbar-right']}>
        {
          props.config?.right
            .filter(x => (!props.config?.[x]?.permissions || analysisPermissionsAndOr(props.config?.[x].permissions)) && (!props.config?.[x]?.roles || analysisRolesAndOr(props.config?.[x].roles)))
            .map((item: any, index: number) => {
              if (item) {
                return ToolbarBtn(item);
              }
            })
        }
      </div>
    )
    return () => (
      hasToolbar.value && <div class={styles.toolbar}>
        <ToolbarLeft />
        <ToolbarRight />
      </div>
    )
  }
})